const { readJSON, writeFile, readTestFileDir } = require('../utils/index')

const path = require('path')
const { get: getSubject } = require('./subject')
const DirName = 'test'
const setTestFileName = (name, num) => {
  name = [Date.now(), num > 9 ? num : ('0' + num), name].join('-')
  return path.join(DirName, name)
}

const splitName = (fileName) => {
  const arr = fileName.split('-')
  return {
    dt: arr[0],
    num: arr[1],
    name: arr[2]
  }
}

const get = () => {
  const testFileList = readTestFileDir()
  const list = testFileList.map(it => {
    return splitName(it)
  })

  return { list }
}
const getId = (dt) => {
  const subs = getSubject().list
  const testFileList = readTestFileDir()
  const fileName = testFileList.find(it => it.startsWith(dt))
  const data = readJSON(path.join(DirName, fileName))

  const list = data.ids.map(it => {
    const d = subs.find(sub => sub.id === it)
    return d
  })
  return { list, ...splitName(fileName) }
}

const addSub = (testId, subId) => {
  const testFileList = readTestFileDir()
  let fileName = testFileList.find(it => it.startsWith(testId))
  if (!fileName) {
    console.log(testFileList, testId)
    return false
  }
  fileName = path.join(DirName, fileName)
  const data = readJSON(fileName)

  data.ids.push(subId)

  writeFile(fileName, JSON.stringify(data))
  console.log(fileName)
  return data
}

const delSub = (testId, subId) => {
  const testFileList = readTestFileDir()
  let fileName = testFileList.find(it => it.startsWith(testId))
  if (!fileName) {
    console.log(testFileList, testId)
    return false
  }
  fileName = path.join(DirName, fileName)
  const data = readJSON(fileName)

  data.ids = data.ids.filter(item => item !== subId)

  writeFile(fileName, JSON.stringify(data))
  console.log(fileName)
  return data
}

// 导出测试
const exportTest = (id) => {
  return { id, msg: '导出成功' }
}

const add = ({ testName, ids }) => {
  console.log('addTest....', testName, ids)
  writeFile(setTestFileName(testName, ids.length), JSON.stringify({ ids }))
  return { success: true }
}

module.exports = {
  getId,
  get,
  add,
  exportTest,
  addSub,
  delSub
}
